package com.hourse.app.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 用于创建连接进行接口调用测试
 *
 */
//@Configuration
public class HttpUtil {


    private static String HX_SMS_CDKEY;

    private static String HD_SMS_PASSWORD;

    private static String HD_SMS_SERVICE_URL;

    @Value("${HX_SMS_CDKEY}")
    public  void setHxSmsCdkey(String hxSmsCdkey) {
        HX_SMS_CDKEY = hxSmsCdkey;
    }

    @Value("${HD_SMS_PASSWORD}")
    public  void setHdSmsPassword(String hdSmsPassword) {
        HD_SMS_PASSWORD = hdSmsPassword;
    }

    @Value("${HD_SMS_SERVICE_URL}")
    public  void setHdSmsServiceUrl(String hdSmsServiceUrl) {
        HD_SMS_SERVICE_URL = hdSmsServiceUrl;
    }


    /**
     * 创建CloseableHttpClient连接
     *
     * @param url
     * @return
     */
    private static CloseableHttpClient create(String url) {
        if (url.startsWith("http:")) {
            return HttpClients.createDefault();
        }
        CloseableHttpClient client = null;
        try {
            SSLContext ssl = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ssl);
            client = HttpClients.custom().setSSLSocketFactory(ssf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return client;
    }

    /**
     * 关闭连接
     *
     * @param client
     */
    private static void close(CloseableHttpClient client, CloseableHttpResponse response) {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * get方法
     *
     * @param url
     * @param map
     * @return
     */
    public static String get(String url, Map<String, String> map) throws Exception {
        CloseableHttpClient create = create(url);
        //组装数据
        URI uri = getUrl(url, map);
        HttpGet get = new HttpGet(uri);
        //执行请求
        CloseableHttpResponse response = null;
        //result响应的结果
        String result = null;
        response = create.execute(get);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        close(create, response);
        //解析返回的内容
        return result;
    }

    /**
     * 生成get方式的url形式
     *
     * @param url
     * @param map
     * @return
     */
    private static URI getUrl(String url, Map<String, String> map) {
        URIBuilder builder = null;
        try {
            builder = new URIBuilder(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        Set<String> set = map.keySet();
        for (String key : set) {
            builder.addParameter(key, map.get(key));
        }
        URI uri = null;
        try {
            uri = builder.build();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return uri;
    }

    /**
     * post方法
     *
     * @param url
     * @param map
     * @return
     */
    public static String post(String url, Map<String, String> map) throws Exception {
        CloseableHttpClient create = create(url);
        HttpPost post = new HttpPost(url);
        //组装数据到请求体
        UrlEncodedFormEntity formEntity = postEntity(map);
        post.setEntity(formEntity);
        //执行请求
        CloseableHttpResponse response = null;
        //result响应的结果
        String result = null;
        response = create.execute(post);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity, "utf-8");
        close(create, response);
        //解析返回的内容
        return result;
    }

    public static String postBaidu(String url, Map<String, String> map) throws Exception {

        CloseableHttpClient create = create(url);
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type","application/x-www-form-urlencoded");

        //组装数据到请求体
        UrlEncodedFormEntity formEntity = postEntity(map);
        post.setEntity(formEntity);
        //执行请求
        CloseableHttpResponse response = null;
        //result响应的结果
        String result = null;
        response = create.execute(post);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity, "utf-8");
        close(create, response);
        //解析返回的内容
        return result;
    }

    public static String postJson(String url, String jsonData) throws Exception {

        CloseableHttpClient create = create(url);
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type","application/json");
        //组装数据到请求体
        StringEntity requestEntity = new StringEntity(jsonData,"utf-8");
        post.setEntity(requestEntity);
        //执行请求
        CloseableHttpResponse response = null;
        //result响应的结果
        String result = null;
        response = create.execute(post);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity, "utf-8");
        close(create, response);
        //解析返回的内容
        return result;
    }

    public static String postJsonForMuBai(String token,String url, String jsonData) throws Exception {

        CloseableHttpClient create = create(url);
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type","application/json");
        post.setHeader("token",token);
        //组装数据到请求体
        StringEntity requestEntity = new StringEntity(jsonData,"utf-8");
        post.setEntity(requestEntity);
        //执行请求
        CloseableHttpResponse response = null;
        //result响应的结果
        String result = null;
        response = create.execute(post);
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity, "utf-8");
        close(create, response);
        //解析返回的内容
        return result;
    }

    /**
     * 用于创建post请求时的请求体
     *
     * @param map
     * @return
     */
    private static UrlEncodedFormEntity postEntity(Map<String, String> map) {
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Set<String> mapSet = map.keySet();
        for (String key : mapSet) {
            BasicNameValuePair basic = new BasicNameValuePair(key, map.get(key));
            list.add(basic);
        }
        UrlEncodedFormEntity formEntity = null;
        try {
            formEntity = new UrlEncodedFormEntity(list, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return formEntity;
    }


    public static String sendMessage(String message, String phone) {
        String result = "ERROR";
        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("cdkey", HX_SMS_CDKEY);
            params.put("password", HD_SMS_PASSWORD);
            params.put("message", message);
            params.put("phone", phone);
            String str = post(HD_SMS_SERVICE_URL, params);
            String err = xmlAnalyze(str, "error");
            result = xmlAnalyze(str, "message");
            if (!"0".equals(err)) {
                return result;
            }

            return "SUCCESS";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }


  public static String POST_JSON(String url, Map<String,String> headerMap, String jsonData) throws Exception {

    CloseableHttpClient create = create(url);
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type","application/json");

    for(Map.Entry<String,String> header: headerMap.entrySet()){
      post.setHeader(header.getKey(),header.getValue());
    }

    //组装数据到请求体
    StringEntity requestEntity = new StringEntity(jsonData,"utf-8");
    post.setEntity(requestEntity);
    //执行请求
    CloseableHttpResponse response = null;
    //result响应的结果
    String result = null;
    response = create.execute(post);
    HttpEntity entity = response.getEntity();
    result = EntityUtils.toString(entity, "utf-8");
    close(create, response);
    //解析返回的内容
    return result;
  }




    public static String xmlAnalyze(String xml, String node) {
        String value = "";
        Pattern p = Pattern.compile("<" + node + ">(.*)</" + node + ">");
        Matcher m = p.matcher(xml);
        if (m.find()) value = m.group(1);
        return value;
    }

    public static void main(String[] args) {



//        String result = "ERROR";
//        try {
//
//            String str1 = "玲珑心意哈根达斯月饼冰淇淋&购买送联通流量活动邀请您参加，访问http://www.gocreditfintech.com:8080/ 可参与本活动，如有疑问请拨打 400-8211-400";
//            Map<String, String> params = new HashMap<String, String>();
//            params.put("cdkey", "8SDK-EMY-6699-RHXOR");
//            params.put("password", "095887");
//            params.put("message", "[月饼电子券]" +str1);
//            params.put("phone", "13260394418");
//            String str = post("http://hprpt2.eucp.b2m.cn:8080/sdkproxy/sendsms.action", params);
//            System.out.println("str : " + str);
//            String err = xmlAnalyze(str, "error");
//            result = xmlAnalyze(str, "message");
//            if (!"0".equals(err)) {
//            }
//
//            System.out.println("--" + result);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }







    }


}
